# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt


from collections import defaultdict
from itertools import chain

import frappe
from frappe import _
from frappe.query_builder import Criterion
from frappe.utils import flt, getdate

import erpnext
from erpnext.accounts.report.balance_sheet.balance_sheet import (
    get_chart_data as get_bs_chart_data,
    get_provisional_profit_loss,
    get_report_summary as get_bs_summary,
)
from erpnext.accounts.report.cash_flow.cash_flow import (
    add_total_row_account,
    get_account_type_based_gl_data,
    get_cash_flow_accounts,
    get_report_summary as get_cash_flow_summary,
)
from erpnext.accounts.report.financial_statements import (
    filter_out_zero_value_rows,
    get_fiscal_year_data,
    get_period_list,  # 导入get_period_list
    sort_accounts,
)
from erpnext.accounts.report.profit_and_loss_statement.profit_and_loss_statement import (
    get_chart_data as get_pl_chart_data,
    get_net_profit_loss,
    get_report_summary as get_pl_summary,
)
from erpnext.accounts.report.utils import convert, convert_to_presentation_currency
from erpnext.accounts.utils import get_zero_cutoff

# 从原文件导入基础函数
from erpnext.accounts.report.consolidated_financial_statement.consolidated_financial_statement import (
    get_account_type_based_data,
    get_balance_sheet_data,
    get_columns,
    get_companies,
    get_company_currency,
    get_data,
    get_income_expense_data,
    get_opening_balance,
    get_root_account_name,
    prepare_companywise_opening_balance,
)


def execute(filters=None):
    columns, data, message, chart = [], [], [], []

    if not filters.get("company"):
        return columns, data, message, chart

    # 处理多报表选择（默认至少选择一个）
    selected_reports = filters.get("report") or ["Balance Sheet"]
    if not isinstance(selected_reports, list):
        selected_reports = [selected_reports]

    # 获取周期列表（修复参数传递）
    period_list = get_period_list(
        filters.from_fiscal_year,
        filters.to_fiscal_year,
        filters.period_start_date,
        filters.period_end_date,
        filters.filter_based_on,
        filters.get("periodicity", "Yearly"),  # 提供默认周期
        company=filters.company,
    )
    
    fiscal_year = get_fiscal_year_data(filters.get("from_fiscal_year"), filters.get("to_fiscal_year"))
    companies_column, companies = get_companies(filters)
    columns = get_columns(companies_column, filters)

    combined_data = []
    combined_chart = {"data": {"labels": [], "datasets": []}}
    combined_summary = []

    # 处理每个选中的报表
    for report in selected_reports:
        if report == "Balance Sheet":
            bs_data, bs_message, bs_chart, bs_summary = get_balance_sheet_data(
                fiscal_year, companies, columns, filters
            )
            combined_data.extend(bs_data)
            message = bs_message or message
            if bs_chart:
                combined_chart["data"]["datasets"].extend(bs_chart["data"]["datasets"])
        
        elif report == "Profit and Loss Statement":
            pl_data, pl_message, pl_chart, pl_summary = get_profit_loss_data(
                fiscal_year, companies, columns, filters
            )
            combined_data.extend(pl_data)
            message = pl_message or message
            if pl_chart:
                combined_chart["data"]["datasets"].extend(pl_chart["data"]["datasets"])
        
        elif report == "Cash Flow":
            # 传递period_list参数给现金流数据获取函数
            cf_data, cf_summary = get_cash_flow_data(fiscal_year, companies, filters, period_list)
            combined_data.extend(cf_data)
            combined_summary.extend(cf_summary)

    # 去重并合并图表标签
    if combined_chart["data"]["datasets"]:
        all_labels = []
        for ds in combined_chart["data"]["datasets"]:
            all_labels.extend(ds.get("labels", []))
        combined_chart["data"]["labels"] = list(dict.fromkeys(all_labels))  # 去重
        combined_chart["type"] = "bar"  # 默认为柱状图
        combined_chart["fieldtype"] = "Currency"
        combined_chart["currency"] = get_company_currency(filters)

    # 合并报表摘要
    report_summary = []
    if "Balance Sheet" in selected_reports and 'bs_summary' in locals():
        report_summary.extend(bs_summary)
    if "Profit and Loss Statement" in selected_reports and 'pl_summary' in locals():
        report_summary.extend(pl_summary)
    if "Cash Flow" in selected_reports:
        report_summary.extend(combined_summary)

    return columns, combined_data, message, combined_chart, report_summary


# 复用原文件中的利润表数据获取函数
def get_profit_loss_data(fiscal_year, companies, columns, filters):
    income, expense, net_profit_loss = get_income_expense_data(companies, fiscal_year, filters)
    company_currency = get_company_currency(filters)

    data = []
    data.extend(income or [])
    data.extend(expense or [])
    if net_profit_loss:
        data.append(net_profit_loss)

    chart = get_pl_chart_data(filters, columns, income, expense, net_profit_loss, company_currency)

    report_summary, primitive_summary = get_pl_summary(
        companies, "", income, expense, net_profit_loss, company_currency, filters, True
    )

    return data, None, chart, report_summary


# 修复现金流数据获取函数，添加period_list参数
def get_cash_flow_data(fiscal_year, companies, filters, period_list):
    cash_flow_accounts = get_cash_flow_accounts()

    income, expense, net_profit_loss = get_income_expense_data(companies, fiscal_year, filters)

    data = []
    summary_data = {}
    company_currency = get_company_currency(filters)

    for cash_flow_account in cash_flow_accounts:
        section_data = []
        data.append(
            {
                "account_name": cash_flow_account["section_header"],
                "parent_account": None,
                "indent": 0.0,
                "account": cash_flow_account["section_header"],
            }
        )

        if len(data) == 1:
            # 添加净利润到经营活动部分
            if net_profit_loss:
                net_profit_loss.update(
                    {"indent": 1, "parent_account": cash_flow_accounts[0]["section_header"]}
                )
                data.append(net_profit_loss)
                section_data.append(net_profit_loss)

        for account in cash_flow_account["account_types"]:
            account_data = get_account_type_based_data(
                account["account_type"], companies, fiscal_year, filters
            )
            account_data.update(
                {
                    "account_name": account["label"],
                    "account": account["label"],
                    "indent": 1,
                    "parent_account": cash_flow_account["section_header"],
                    "currency": company_currency,
                }
            )
            data.append(account_data)
            section_data.append(account_data)

        add_total_row_account(
            data,
            section_data,
            cash_flow_account["section_footer"],
            companies,
            company_currency,
            summary_data,
            filters,
            True,
        )

    add_total_row_account(
        data, data, _("Net Change in Cash"), companies, company_currency, summary_data, filters, True
    )

    report_summary = get_cash_flow_summary(summary_data, company_currency)

    return data, report_summary